package com.ramos.kuaixiao.ui;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.adapter.DataReportAdapter;
import com.ramos.kuaixiao.db.OrderDB;
import com.ramos.kuaixiao.entity.DataReport;
import com.ramos.kuaixiao.entity.FindOrderDetail;
import com.ramos.kuaixiao.utils.CommonLoading;
import com.ramos.kuaixiao.utils.Utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DataReportActivity extends BaseActivity implements View.OnClickListener {
    private final static String TAG = "DataReportActivity";
    private TextView tv_aboutus;
    private Context mContext;
    CommonLoading loading;
    LinearLayout title_reback;
    ListView mListView;
    LineChart mLineChart;
    PieChart mPieChart;
    DataReportAdapter mAdapter;
    TableLayout child_layout;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;

    private int[] colors1;//颜色集合
    private String[] labels;//标签文本
    private Float[] datas ;//数据，可以是任何类型的数据，如String,int
    List<Float> prices=new ArrayList<>();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_report);
        mContext = this;
        tv_aboutus = findViewById(R.id.title_text);
        tv_aboutus.setText("数据报表");
        title_reback = findViewById(R.id.title_reback);
        title_reback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mLineChart= findViewById(R.id.chart);
        mListView= findViewById(R.id.listview);
        mPieChart = findViewById(R.id.piechart);
        child_layout = findViewById(R.id.child_layout);
        List<FindOrderDetail> list = new OrderDB().findAllOrder();
      /*  List<Entry> entries = new ArrayList<>();

        for (FindOrderDetail data : list) {
            entries.add(new Entry(data.getOrderTotalPrice(), data.getCustmerName()));
        }*/
        Set<String> set = new HashSet<>();
        for(FindOrderDetail order : list){
            set.add(order.getCustmerName());
        }
        Log.d(TAG, "set:"+set.size());
        Map<String, Float> map = new HashMap<>();
        List<DataReport> reports = new ArrayList<>();
        for(String s : set){
            DataReport dataReport = new DataReport();
            dataReport.setCustmerName(s);
            float total = 0;
            int count = 0;
            for(FindOrderDetail order : list){
                if(s.equals(order.getCustmerName())){
                    total += Double.valueOf(order.getOrderTotalPrice());
                    ++count;
                }
            }
            dataReport.setOrderTotalPrice(total);
            dataReport.setTotal(count);
            //map.put(s, total);
            //Log.d(TAG, "map:"+s + " " + total);
            reports.add(dataReport);
        }

        sortTotal(reports);

        List<PieEntry> entries = new ArrayList<>();

       /* for (Map.Entry<String, Float> entry : map.entrySet()) {
            //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            Log.d(TAG, "map1:"+entry.getValue()+ " " + entry.getKey());
            entries.add(new PieEntry(entry.getValue(), entry.getKey()));
        }*/
        if(reports.size() < 10){
            for(DataReport dataReport : reports){
                entries.add(new PieEntry(dataReport.getOrderTotalPrice(), dataReport.getCustmerName()));
                prices.add(dataReport.getOrderTotalPrice());
            }
        } else {
            for(int i = 0 ; i < 10 ;i++){
                entries.add(new PieEntry(reports.get(i).getOrderTotalPrice(), reports.get(i).getCustmerName()));
                prices.add(reports.get(i).getOrderTotalPrice());
            }
        }

        PieDataSet set1 = new PieDataSet(entries, "");
        ArrayList<Integer> colors = new ArrayList<>();
        colors.add(getResources().getColor(R.color.colorAccent));
        colors.add(getResources().getColor(R.color.bottom_tab_unselected));
        colors.add(getResources().getColor(R.color.colorPrimaryDark));
        colors.add(getResources().getColor(R.color.color_02A5E6));
        colors.add(getResources().getColor(R.color.color_button));
        colors.add(getResources().getColor(R.color.color_FF8C01));

        colors.add(getResources().getColor(R.color.bill_reject));
        colors.add(getResources().getColor(R.color.black2));
        colors.add(getResources().getColor(R.color.app_red));
        colors.add(getResources().getColor(R.color.viewfinder_border));
        colors.add(ColorTemplate.getHoloBlue());
        set1.setColors(colors);
        set1.setSliceSpace(3f);
        set1.setSelectionShift(5f);
        set1.setDrawValues(false);

        PieData data = new PieData(set1);
        data.setDrawValues(true);
        data.setValueTextSize(12f);

        Log.d(TAG, "data:"+data.getDataSet().getLabel());
        if(data != null) {
            mPieChart.setData(data);
            mPieChart.invalidate(); // refresh
            mPieChart.setDrawCenterText(true);
            mPieChart.setHoleRadius(0f);
            mPieChart.setTransparentCircleRadius(0f);
            Description description = new Description();
            description.setText("排名前十的数据");
            mPieChart.setDescription(description);

            mPieChart.setDrawSliceText(false);
            mPieChart.highlightValues(null);

            Legend l = mPieChart.getLegend();
            l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
            l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
            l.setOrientation(Legend.LegendOrientation.VERTICAL);
            l.setDrawInside(false);
            l.setXEntrySpace(7f);
            l.setYEntrySpace(0f);
            l.setYOffset(0f);
            l.setEnabled(false);//图例不显示
            colors1=l.getColors();
            labels=l.getLabels();
            customizeLegend();
        }

        mAdapter = new DataReportAdapter(DataReportActivity.this, reports);
        mListView.setAdapter(mAdapter);
        Utils.setListViewHeightBasedOnChildren(mListView);
    }

    /**
     * 定制图例，通过代码生成布局
     */
    private void customizeLegend(){
        for(int i=0;i<prices.size();i++){
            LinearLayout.LayoutParams lp=new LinearLayout.
                    LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            lp.weight=1;//设置比重为1
            LinearLayout layout=new LinearLayout(this);//单个图例的布局
            layout.setOrientation(LinearLayout.HORIZONTAL);//水平排列
            layout.setGravity(Gravity.CENTER_VERTICAL);//垂直居中
            layout.setLayoutParams(lp);

            //添加color
            LinearLayout.LayoutParams colorLP=new LinearLayout.
                    LayoutParams(20,20);
            colorLP.setMargins(0, 0, 20, 0);
            LinearLayout colorLayout=new LinearLayout(this);
            colorLayout.setLayoutParams(colorLP);
            colorLayout.setBackgroundColor(colors1[i]);
            layout.addView(colorLayout);

            //添加label
            TextView labelTV=new TextView(this);
            labelTV.setText(labels[i]+" ");
            layout.addView(labelTV);

            //添加data
            TextView dataTV=new TextView(this);
            dataTV.setText(prices.get(i)+"");
            layout.addView(dataTV);

            child_layout.addView(layout);//legendLayout为外层布局即整个图例布局，是在xml文件中定义
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
             default:
                 break;
        }
    }


    private void sortTotal(List<DataReport> reports) {
        Collections.sort(reports, new Comparator<DataReport>() {

            @Override
            public int compare(DataReport o1, DataReport o2) {
                float total1 = 0;
                float total2 = 0;
                try {
                    total1 = o1.getOrderTotalPrice();
                    total2 = o2.getOrderTotalPrice();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 按照时间进行降序排列
                if (total1 > total2) {
                    return -1;
                }
                if (total1 == total2) {
                    return 0;
                }
                return 1;
            }
        });
    }
}


